/* 
 * LockManager.java 29.06.2011
 *  
 *  
 * Candidate: Alessandra Otterbach
 * Prometric ID: Algisina1
 * Username: Algisina
 *  
 * Sun Certified Developer for Java 2 Platform, Standard Edition Programming 
 * Assignment (CX-310-252A)
 *  
 * This class is part of the Programming Assignment of the Sun Certified 
 * Developer for Java 2 Platform, Standard Edition certification program, must 
 * not be used out of this context and must be used exclusively by Sun 
 * Microsystems, Inc. 
 */  
package suncertify.db;

import java.util.HashMap;
import java.util.Map;

import suncertify.db.exc.RecordNotFoundException;
import suncertify.db.exc.SecurityException;

/**
 * @author Alessandra Otterbach
 *
 */
public class LockManager {
    
    private Map<Integer, Long> lockedRecords = new HashMap<Integer, Long>();
    
    public long lock(int recNo) throws RecordNotFoundException
    {
	// Find out if record already is locked
	if (lockedRecords.containsKey(recNo)) {
	    // TODO wait...
	}
	// After waiting, verify if the record still exists (it may have been
	// deleted)
	long cookieValue = System.currentTimeMillis();
	lockedRecords.put(recNo, cookieValue);

	return cookieValue;
    }
    
    public void unlock(int recNo, long cookie) throws RecordNotFoundException,
    SecurityException {
	// Check if record is locked at all and with the given cookie, if not,
	// SecExc
	// Cookie must be the cookie
	// returned when the record was locked
	// Check if record is locked at all (!= null) and with given lockCookie
	if (!checkLocked(recNo, cookie)) {
	    throw new SecurityException();
	}
	// Remove lock
	lockedRecords.remove(recNo);
    }
    
    /**
     * TODO Auslagern in LockManager! Check if record is locked at all (!= null)
     * and with given lockCookie
     * 
     * @return
     */
    public boolean checkLocked(int recNo, long lockCookie) {

	// Check if record is locked at all (!= null) and with given lockCookie
	if (lockedRecords.get(recNo) == null
		|| lockCookie != lockedRecords.get(recNo)) {
	    return false;
	}
	return true;
    }
    
    
}
